/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jl.security.pad;

import java.security.GeneralSecurityException;

/**
 *
 * @author Administrator
 */
public class ISO9797M2 implements IPad {

    @Override
	public byte[] pad(byte[] data) {
        int len = (data.length / 8 + 1) * 8;
        byte[] dataTemp = new byte[len];
        System.arraycopy(data, 0, dataTemp, 0, data.length);
        byte[] padding = new byte[]{(byte) 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
        System.arraycopy(padding, 0, dataTemp, data.length, dataTemp.length - data.length);
        return dataTemp;
    }

    @Override
	public byte[] removePad(byte[] data) throws GeneralSecurityException {
        int index = 0;
        for (int i = data.length - 1; i >= 0; i--) {
            if (data[i] == (byte) 0x80) {
                index = i;
                break;
            }
            if (data.length - i >= 8) {
                throw new GeneralSecurityException("Padding type may be wrong");
            }
        }
        byte[] dataTemp = new byte[index];
        System.arraycopy(data, 0, dataTemp, 0, index);
        return dataTemp;
    }
}
